package com.example.ota_ble.ble.connect

import android.Manifest
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattService
import android.util.Log
import androidx.annotation.RequiresPermission

/*
*   gatt 管理类，负责注册读写回调事件，读和写
* */
class buletoothGattManage {
    var TAG = "rocjan.buletoothGattManage"
    lateinit var blueGattCallBk:bluetoothGattCallBk

    lateinit var blueGatt:BluetoothGatt
    //蓝牙ota的服务和特征
    lateinit var ota_ble_service:BluetoothGattService
    lateinit var ota_ble_characteristic:BluetoothGattCharacteristic

    //蓝牙mcu的服务和特征
    lateinit var ota_mcu_service:BluetoothGattService
    lateinit var ota_mcu_characteristic_ctrl:BluetoothGattCharacteristic
    lateinit var ota_mcu_characteristic_data:BluetoothGattCharacteristic
    //蓝牙mcu的服务和特征
    lateinit var test_service:BluetoothGattService
    lateinit var test_characteristic:BluetoothGattCharacteristic
    init {
        this.blueGattCallBk = bluetoothGattCallBk(this)
    }
    fun get_gattRecall():bluetoothGattCallBk = this.blueGattCallBk

    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun writeDataToCharacteristic(characteristic: BluetoothGattCharacteristic, data: ByteArray) {
        // 将数据转换为字节数组



        // 设置特征的值
        characteristic.value = data
        //Log.i(TAG,  "realwrite:"+ data.joinToString(", ") { "0x${it.toUByte().toString(16).padStart(2, '0')}" })

        // 向设备写入数据
        val status = this.blueGatt.writeCharacteristic(characteristic)

        if (status) {
            Log.d(TAG, "Write initiated")
        } else {
            Log.d(TAG, "Failed to initiate write")
        }
    }
}